﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


using ClassCommon;
using ClassWeb.App_Data;
using ClassBLL;
using ClassModel;

namespace ClassWeb.Controllers
{
    public class UtilityController : BaseController
    {
        //
        // GET: /Utility/

        /// <summary>
        /// 返回图片验证码API
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ValidateCode()
        {
            //首先实例化验证码的类  
            ValidateCodeHelper validateCode = new ValidateCodeHelper();
            //生成验证码指定的长度  
            string code = validateCode.GetRandomString(4);

            string encryptCode = EncryptHelper.Encrypt(code, string.Empty);
            // 验证码cookie存储
            HttpCookieHelper.SetCookie(ConfigSetting.Cookie_ValidateCode, encryptCode);

            //创建验证码的图片  
            byte[] bytes = validateCode.CreateImage(code);
            //最后将验证码返回  
            return File(bytes, @"image/jpeg");
        }


        /// <summary>
        /// 文件上传API
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult FileUpload(string taskId, int fileId, string typeValue)
        {
            this.Response.ContentType = "application/json";

            if (this.CurrentUser == null) return Json(new { status = false }, JsonRequestBehavior.AllowGet);

            UploadFileInfo fileInfo = HttpPostFileHelper.FileUploadAndSave();

            t_class_fileupload model = new t_class_fileupload();
            model.userId = this.CurrentUser.id;
            model.orginName = fileInfo.orginName;
            model.newName = fileInfo.newName;
            model.fileSize = fileInfo.fileSize;
            model.extensionName = fileInfo.extensionName;
            model.savePath = fileInfo.savePath;
            model.contentType = fileInfo.contentType;
            model.uploadDate = DateTime.Now;
            model.TaskId = string.IsNullOrEmpty(taskId) ? -1 : Convert.ToInt32(EncryptHelper.Decrypt(taskId));

            int inscreaseFileid = t_class_user_fileupalod_BLL.InsertFileUpload(model);

            #region 上传文件之前，根据提交的表格数据是否包含fileid，决定是否删除之前旧的数据

            if (fileId != 0)
            {
                // 删除由上一个excel文件产生的一大坨数据.

                t_class_Common_BLL.clearExcelUploadFilePreData(fileId);
            }


            #endregion

            // application/vnd.ms-excel
            if (typeValue == "csv")
            {
                return Json(new { status = true, extension = "csv" }, JsonRequestBehavior.AllowGet);
            }

            #region 文件上传完毕之后 -- 插入老师、课程、班级、排课数据等信息
            string filePath = this.Server.MapPath(model.savePath);

            GetClassAssociateInfoHelper gah = new GetClassAssociateInfoHelper(filePath);

            // 插入老师信息
            var teachers = gah.GetTeachers();
            if (teachers != null)
            {
                List<t_class_tearcher> teachersList = new List<t_class_tearcher>();
                teachers.ForEach(teachername =>
                {
                    t_class_tearcher t = new t_class_tearcher();
                    t.fileid = inscreaseFileid;
                    t.teacher = teachername;
                    t.createtime = DateTime.Now;

                    teachersList.Add(t);
                });


                t_class_teacher_BLL.InsertTeachers(teachersList);
            }

            // 插入班级信息

            var classes = gah.GetClasses();
            if (classes != null)
            {
                List<t_class_class> classList = new List<t_class_class>();
                classes.ForEach(classname =>
                {
                    t_class_class c = new t_class_class();
                    c.classname = classname;
                    c.createtime = DateTime.Now;
                    c.fileid = inscreaseFileid;

                    classList.Add(c);
                });

                t_class_classes_BLL.InsertClasses(classList);
            }

            // 插入课程信息

            var courseNames = gah.GetCourses();
            if (courseNames != null)
            {
                List<t_class_course> courseList = new List<t_class_course>();
                courseNames.ForEach(courseName =>
                {
                    t_class_course course = new t_class_course();
                    course.createtime = DateTime.Now;
                    course.coursename = courseName;
                    course.fileid = inscreaseFileid;

                    courseList.Add(course);
                });

                t_class_course_BLL.InsertCoures(courseList);
            }

            // 插入年级信息
            var gradename = gah.GetGrade();
            if (!string.IsNullOrEmpty(gradename))
            {
                t_class_grade grade = new t_class_grade();
                grade.gradename = gradename;
                grade.fileid = inscreaseFileid;
                grade.createtime = DateTime.Now;

                t_class_grade_BLL.InsertGradeInfo(grade);

            }

            // 插入老师和课程的关系
            var relationShipTeacherAndCourse = gah.GetRelationWithTeacherAndCourse();
            if (relationShipTeacherAndCourse != null)
            {
                t_class_teacher_course_BLL.InsertRelationships(relationShipTeacherAndCourse, inscreaseFileid);
            }

            // 插入排班信息
            var scheduleClassDicts = gah.GetScheduleClassData();
            if (scheduleClassDicts != null)
            {
                t_class_schedule_BLL.InsertScheduleClasses(scheduleClassDicts, inscreaseFileid);
            }

            #endregion

            return Json(new { status = true, uploadInfo = fileInfo }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="phoneNum">手机号码</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult getPhoneValidateCode(string phoneNum)
        {
            this.Response.ContentType = "application/json";

            // 服务端验证
            if (!RegexHelper.isPhoneNum(phoneNum)) return Redirect("/tip?tip=手机号码格式不正确");

            // 发送手机验证码
            bool isSend = PhoneValidateCodeHelper.SendValidatePhoneCode(phoneNum);

            return Json(new { status = isSend }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 手机验证码验证
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult PhoneCodeValidate(string code)
        {
            this.Response.ContentType = "application/json";

            if (string.IsNullOrEmpty(code)) return Redirect("/tip?tip=验证码不能为空");
            if (!RegexHelper.isPhoneCodeValidate(code)) return Redirect("/tip?tip=验证码格式不正确");

            string cookiePhoneCode = HttpCookieHelper.getPhoneValidateCode();

            return Json(new { isPass = cookiePhoneCode.ToLower() == code.ToLower() }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 检查用户附加信息是否存在
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CheckAttachmentExists()
        {
            this.Response.ContentType = "application/json";

            if (this.CurrentUser == null)
                return Json(new { status = false });

            int id = t_class_attachment_info_BLL.CheckAttachmentExists(this.CurrentUser.id);

            return Json(new { status = id != 0 });
        }

        /// <summary>
        /// 检查用户是否登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CheckUserIsLogin()
        {
            this.Response.ContentType = "application/json";

            return Json(new { isLogin = this.CurrentUser != null }, JsonRequestBehavior.AllowGet);
        }


        #region 删除指定账户信息(测试需要)
        /// <summary>
        ///  删除指定账号信息
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult DeleteAccount(string account)
        {
            this.Response.ContentType = "application/json";

            if (string.IsNullOrEmpty(account)) return Json(new { status = false, info = "账户名不能为空!!" }, JsonRequestBehavior.AllowGet);


            int reuslt = t_classDemo_UserInfo_BLL.DeleteWithAccount(account);

            return Json(new
            {
                status = true,
                info = string.Format("[{0}] 删除成功!", account)
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
